package com.eversec.util.xml;

import java.io.File;

import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import com.eversec.action.check.LogicCheck;
import com.eversec.model.exception.FileCheckExceptionBean;

/**
 * XML校对工具
 * 
 * @author Administrator
 * 
 */
public class ValidateXML {

	/**
	 * 基于xsd文档进行格式校对
	 * 
	 * @param xsdpath
	 * @param xmlpath
	 * @return
	 */
	public static FileCheckExceptionBean validateXmlBasedOnXsd(String xsdpath, String xmlpath) {
		boolean flag = false;
		Exception e = new Exception();
		try {
			// 建立schema工厂
			SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
			// 建立验证文档文件对象，利用此文件对象所封装的文件进行schema验证
			File schemaFile = new File(xsdpath);
			// 利用schema工厂，接收验证文档文件对象生成Schema对象
			Schema schema = schemaFactory.newSchema(schemaFile);
			// 通过Schema产生针对于此Schema的验证器，利用schenaFile进行验证
			Validator validator = schema.newValidator();
			// 得到验证的数据源
			Source source = new StreamSource(xmlpath);
			// 开始验证，成功输出success!!!，失败输出fail
			validator.validate(source);
			flag = true;
		} catch (Exception ex) {
			e = ex;
		}
		return new FileCheckExceptionBean(flag, e);
	}

	/**
	 * 基于工程代码逻辑进行格式校对
	 * 
	 * @param checkType
	 *            传过来的检测类型为 01-07 需要转化为1-7 1-7检测类型处理过程不同
	 * @param xmlPath
	 * @return
	 */
	public static FileCheckExceptionBean validateXmlBasedOnLogic(String checkType, String xmlPath) {
		boolean flag = false;
		Exception e = new Exception();

		char checkChar = checkType.charAt(1);

		try {
			switch (checkChar) {
			case '1':
				flag = LogicCheck.basicInfoCheck(xmlPath);
				break;
			case '2':
				break;
			case '3':
				break;
			case '4':
				break;
			case '5':
				break;
			case '6':
				break;
			case '7':
				break;
			default:
				break;
			}
		} catch (Exception ex) {
			e = ex;
		}
		return new FileCheckExceptionBean(flag, e);
	}

	// public static void main(String[] args) {
	// try {
	// //
	// validatexml("/Users/lilizhao/Downloads/l刘荣靖资料/IDC-管局端实施测试资料/03schema/04 监测日志上报校验/monitorResult.xsd",
	// // "/Users/lilizhao/Downloads/lndx/4/2014-05-21/1400637061.xml");
	// validatexml("F:\\git\\IdcDetecteTool\\config\\01\\filecheck.xsd",
	// "C:\\Documents and Settings\\Administrator\\桌面\\zhujunliang.xj.xml");
	// } catch (SAXException e) {
	// e.printStackTrace();
	// } catch (IOException e) {
	// e.printStackTrace();
	// }
	// }
}